package com.zxhhyj.storm.common

import com.zxhhyj.storm.schema.Column
import com.zxhhyj.storm.schema.Table
import kotlin.reflect.KClass
import kotlin.reflect.full.primaryConstructor

@Suppress("UNCHECKED_CAST")
@OptIn(ExperimentalStdlibApi::class)
actual fun <T> packing(targetTable: Table<T>, selectColumns: List<Column<*, *>>, values: Map<String, *>): T {
    val entryClass = targetTable::class.supertypes
        .first()
        .arguments
        .first()
        .type
        ?.classifier as KClass<*>

    val constructorParameters = entryClass.primaryConstructor?.parameters
        ?: throw IllegalStateException("实体类 ${entryClass.simpleName} 缺少主构造函数")

    val selectedColumnNames = selectColumns.filterIsInstance(Column.RowBinding::class.java)

    val parameterNames = constructorParameters.associateWith { parameter ->
        val first = selectedColumnNames.firstOrNull { it.selector.name == parameter.name } ?: return@associateWith null
        values[first.fieldName]
    }

    return entryClass.primaryConstructor!!.callBy(parameterNames) as T
}